package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.query.CarPackageAuditQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.business.service.IStatementService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.*;

@Service
@Transactional
public class CarPackageAuditServiceImpl implements ICarPackageAuditService {

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private IStatementService statementService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private IBpmnInfoService bpmnInfoService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private IServiceItemService serviceItemService;
    @Autowired
    private TaskService taskService;


    @Override
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<CarPackageAudit>(carPackageAuditMapper.selectForList(qo));
    }


    @Override
    public void save(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.insert(carPackageAudit);
    }

    @Override
    public CarPackageAudit get(Long id) {
        return carPackageAuditMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
    }

    @Override
    public void delete(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            carPackageAuditMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<CarPackageAudit> list() {
        return carPackageAuditMapper.selectAll();
    }

    @Override
    public InputStream getProcessImgAsStream(Long id) {
        // 根据id获取套餐审核对象
        CarPackageAudit audit = this.get(id);
        // 获取流程实例的id
        String instanceId = audit.getInstanceId();
        // 定义一个空的list
        List<String> highLightedActivities = null;
        // 判断状态，如果是审核中，需要高亮目前运行的节点
        if (CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())){
            // 根据流程实例id获取目前活动的节点
            highLightedActivities = runtimeService.getActiveActivityIds(instanceId);
        }else {
            highLightedActivities = new ArrayList<>();
        }
        // 根据bpmnInfo查询bpmnInfo对象，对象中存储流程定义的id
        BpmnInfo bpmnInfo = bpmnInfoService.get(audit.getBpmnInfoId());
        BpmnModel model = repositoryService.getBpmnModel(bpmnInfo.getActProcessId());
        DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
        return generator.generateDiagram(model,highLightedActivities, Collections.EMPTY_LIST,"宋体","宋体","宋体");
    }

    @Override
    @Transactional
    public void cancelApply(Long id) {
        // 进行合理化校验
        // 只有审核中的记录才可以执行撤销操作
        CarPackageAudit audit = this.get(id);
        if (!CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())){
            throw new BusinessException("只有处于审核中的记录才可以进行撤销操作");
        }
        // 把服务单项的审核状态更新为初始化
        serviceItemService.changeAuditStatus(audit.getServiceItemId(), ServiceItem.AUDITSTATUS_INIT);
        // 把流程实例删除
        runtimeService.deleteProcessInstance(audit.getInstanceId(),"流程撤销");
        // 审核对象的状态设置为已撤销
        carPackageAuditMapper.changeStatus(id,CarPackageAudit.STATUS_CANCEL);
    }

    @Override
    public void audit(Long id, Integer auditStatus, String info) {
        //获取审核对象
        CarPackageAudit audit = this.get(id);
        //合理化校验
        //流程处于审批中才可以进行操作
        if (!CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())) {
            throw new BusinessException("只有处于审核状态的记录才能进行审核操作");
        }
        //只有是受理人才有权限审批
        String userName = ShiroUtils.getUser().getUserName();
        if (CarPackageAudit.STATUS_PASS.equals(auditStatus)) {
            info = userName + "[同意],批注意见:" + info;

        } else {
            info = userName + "[拒绝],批注意见:" + info;
        }
        //设置info 字段的值
        audit.setInfo(audit.getInfo() + "</br>" + info);
        //查询任务
        Task currentTask = taskService.createTaskQuery().
                processInstanceId(audit.getInstanceId()).singleResult();
        //设置auditStatus的值
        taskService.setVariable(currentTask.getId(), "auditStatus", auditStatus);

        taskService.addComment(currentTask.getId(),audit.getInstanceId(),info);
        //完成任务
        taskService.complete(currentTask.getId());

        //下一个节点
        Task nextTask = taskService.createTaskQuery().
                processInstanceId(audit.getInstanceId()).singleResult();

        //根据STATUS_PASS 判断是审核通过或审核拒绝
        if (CarPackageAudit.STATUS_PASS.equals(auditStatus)) {
            if (nextTask != null) {
                //说明还有下一个节点,财务审核
                //设置
                audit.setAuditorId(Long.parseLong(nextTask.getAssignee()));
                audit.setAuditTime(new Date());
            } else {
                //审核通过
                //设置发起审核的记录状态为审核通过
                serviceItemService.changeAuditStatus(audit.getServiceItemId(),ServiceItem.AUDITSTATUS_APPROVED);
                //设置审核状态为通过
                audit.setStatus(CarPackageAudit.STATUS_PASS);

            }

        }else {
            //审核拒绝
            //设置审批记录状态为重新调整
            serviceItemService.changeAuditStatus(audit.getServiceItemId(),ServiceItem.AUDITSTATUS_REPLY);
            //更新审核对象信息中的状态为审核拒绝
            audit.setStatus(CarPackageAudit.STATUS_REJECT);

        }
        //更新数据库中的审核对象信息
        carPackageAuditMapper.updateByPrimaryKey(audit);

    }

    /*public void audit2(Long id, Integer auditStatus, String info) {
        // 合理化检验
        CarPackageAudit carPackageAudit = this.get(id);
        // 只有审核中的流程才可以发起审批
        if (!CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())){
            throw new BusinessException("非法操作");
        }
        // 只有审核人才可以对流程进行审核
        if (!ShiroUtils.getUserId().equals(carPackageAudit.getAuditorId())){
            throw new BusinessException("非法操作");
        }
        // 判断审核人的意见是同意还是拒绝，在备注信息中记录审核人的用户名和意见
        String userName = ShiroUtils.getUser().getUserName();
        if (CarPackageAudit.STATUS_PASS.equals(auditStatus)){
            // 表示审核通过
            info = "用户["+userName+"]同意,备注信息是:"+info;
        }else{
            // 表示审核拒绝
            info = "用户["+userName+"]拒绝备注信息是:"+info;
        }
        // 把备注信息重新回去
        carPackageAudit.setInfo(carPackageAudit.getInfo()+info);
        // 中间漏了三个步骤
        // 1、让工作流activiti的流程往后流转
        Task task = taskService.createTaskQuery().processInstanceId(carPackageAudit.getInstanceId()).singleResult();
        // 2、在任务完成前，设置流程变量auditStatus，这个变量的主要作用还是记录当前的节点负责人是谁
        taskService.setVariable(task.getId(),"auditStatus",auditStatus);
        // 3、完成任务
        taskService.complete(task.getId());
        // 4、设置审核结束时间
        carPackageAudit.setAuditTime(new Date());
        if (CarPackageAudit.STATUS_PASS.equals(auditStatus)){
            // 如果是同意
            // 先判断是否有下一个节点
            task = taskService.createTaskQuery().processInstanceId(carPackageAudit.getInstanceId()).singleResult();
            if (task == null){
                // 如果没有下一个节点，就把审核流程对象设置为审核通过
                carPackageAudit.setStatus(CarPackageAudit.STATUS_PASS);
                // 把服务单项的状态设置为审核通过
                serviceItemService.changeAuditStatus(carPackageAudit.getServiceItemId(),ServiceItem.AUDITSTATUS_APPROVED);
                // 流程做完了，把审核人对象设置为空
                carPackageAudit.setAuditorId(null);
            }else{
                // 如果有下一个节点，就获取审批人的id
                carPackageAudit.setAuditorId(Long.parseLong(task.getAssignee()));
            }
        }else {
            // 如果是拒绝
            // 有可能是店长拒绝或者是财务拒绝
            // 把审批流程对象的状态修改为审核拒绝
            carPackageAudit.setStatus(CarPackageAudit.STATUS_REJECT);
            // 把服务单项中的状态修改为是重新调整
            serviceItemService.changeAuditStatus(carPackageAudit.getServiceItemId(),ServiceItem.AUDITSTATUS_REPLY);
            // 流程做完了，把审核人对象设置为空
            carPackageAudit.setAuditorId(null);
        }
        // 5、对审核的对象进行更新
        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
    }*/
}
